<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, reactive, toRefs } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { BasicTree, TreeActionType } from '/@/components/Tree/index';
  import { assignRoleInfo } from '/@/api/backs/system/role';

  import { formSchema } from './tableData';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';

  export default defineComponent({
    name: 'RoleDrawer',
    components: { BasicDrawer, BasicForm },
    props: {
      type: {
        type: String,
        default: () => {
          return 'add';
        },
      },
      powerInfoList: {
        type: Array,
        default: () => {
          return [];
        },
      },
    },
    emits: ['success', 'register'],
    setup(props, { emit }) {
      console.log(BasicTree);
      const isUpdate = ref(true);
      const asyncExpandTreeRef = ref<Nullable<TreeActionType>>(null);
      const data: any = reactive({
        type: 'add',
        schemas: formSchema,
        powerList: [],
      });

      const [registerForm, { resetFields, setFieldsValue, setProps, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 12, md: 24 },
        fieldMapToTime: [['datetime', ['startTime', 'endTime'], 'YYYY-MM-DD']],
      });
      const formId = ref(null);
      const roleId = ref(null);
      const [registerDrawer, { setDrawerProps }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        formId.value = props.type === 'edit' ? data.record.id : null;
        roleId.value = props.type === 'power' ? data.record.id : null;

        setProps({
          mergeDynamicData: { propsType: props.type },
        });
        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
        }
        if (props.type === 'power') {
          handlePowerInfo(roleId.value);
        }
      });

      async function handlePowerInfo(id) {
        let powerList = await assignRoleInfo({ roleId: id });
        data.powerList = powerList;
        return powerList;
      }

      const getTitle = computed(() =>
        props.type === 'edit' ? '编辑' : props.type === 'add' ? '增加' : '设置权限',
      );

      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          // TODO custom api
          let params = { ...values };

          if (data.powerList.length) {
            params.menuIds = data.powerList;
          }
          if (roleId.value) {
            params.roleId = roleId.value;
          }
          if (formId.value) {
            params.id = formId.value;
          }
          emit('success', params);
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        ...toRefs(data),
        asyncExpandTreeRef,
      };
    },
  });
</script>
